package com.example.hosptial.service;

import com.example.hosptial.config.DeepSeekConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class DeepSeekService {

    @Autowired
    private DeepSeekConfig deepSeekConfig;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void streamResponse(String message, SseEmitter emitter) {
        try {
            URL url = new URL(deepSeekConfig.getBaseUrl() + "/api/generate");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 准备请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-r1:1.5b");
            requestBody.put("prompt", message);
            requestBody.put("stream", true);

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = objectMapper.writeValueAsString(requestBody).getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取流式响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.isEmpty()) continue;
                    
                    try {
                        Map<String, Object> response = objectMapper.readValue(line, Map.class);
                        if (response.containsKey("response")) {
                            String content = (String) response.get("response");
                            emitter.send(content);
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
            
            emitter.complete();
            
        } catch (Exception e) {
            try {
                emitter.send("Error: " + e.getMessage());
                emitter.complete();
            } catch (IOException ex) {
                emitter.completeWithError(ex);
            }
        }
    }
} 